import cgi 
import os 
from google.appengine.ext.webapp import template
from google.appengine.api import users 
from google.appengine.ext import webapp 
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.ext import db
import csv
import datetime
import sys
from pprint import pprint
from StringIO import StringIO
import urllib

# Yahoo stock quote URL
URL = "http://quote.yahoo.com/d/quotes.csv?s=%s&f=snohgl1d1"

class MainPage(webapp.RequestHandler):
	def fetch_quote(self,code):
		url = URL % code
		# fetch
		fp = urllib.urlopen(url)
		try:
			data = fp.read()
		finally:
			fp.close()
		return data
    
	def get(self):
		stock_id = self.request.get('id')
		if stock_id:
			if stock_id.startswith('0'):
				stock_id = stock_id+'.SZ'
			elif stock_id.startswith('6'):
				stock_id = stock_id+'.SS'
		if stock_id:
			data = self.fetch_quote(stock_id)
			template_values = {
				'stockinfo':data,
				}
		else:
			template_values = {
				}
		path = os.path.join(os.path.dirname(__file__), 'stock.html')
		self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication( 
                                     [('/stock', MainPage)], 
                                     debug=True) 
 
def main(): 
    run_wsgi_app(application) 
 
if __name__ == "__main__": 
    main()
